package com.example.seakdreamandroid.whiteNoisePlayer;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.FavoriteActivity;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.MusicStoryPlayerActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.accountInfo.PopupAndDarkenWindow;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.Favorite;
import com.example.seakdreamandroid.entity.Result;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.playHistory.PlayHistoryActivity;
import com.example.seakdreamandroid.sleep.AlarmClockAndPrompt;
import com.example.seakdreamandroid.voiceCommunity.VoiceDescribeActivity;
import com.example.seakdreamandroid.voiceCommunity.VoiceRemarkActivity;
import com.example.seakdreamandroid.whiteNoise.FreeConbination;
import com.example.seakdreamandroid.whiteNoise.OfficialRecommendation;
import com.example.seakdreamandroid.whiteNoise.SleepFriendCreation;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseFreeConbinationChannel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WhiteNoisePlayerActivity extends AppCompatActivity {
    private ImageButton player,share,like,list,alarm,setting;
    private ImageView musicCenter1,musicCenter2,musicPic1,musicPic2,musicPic3;
    //这些是settingPopup弹出的视图里面的控件
    private ImageView voiceImg1,voiceImg2,voiceImg3;
    private SeekBar voiceBar1,voiceBar2,voiceBar3;
    private LinearLayout voice1,voice2,voice3;
    private LinearLayout linearLayout;
    private PopupAndDarkenWindow settingPopup;
    //动画
    private static ObjectAnimator animator1,animator2;
    private static ValueAnimator animator3,animator4;

    private boolean isFavorite = false;
    private User user;
    private Timer timer2;
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            //时间到停止播放
            controller.pausePlay(true);
        }
    };
    private WhiteNoisePlayerService.WhiteNoiseControl controller;
    private Intent intentToHistory, intentToClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WhiteNoisePlayerService.registerForListener(handler);
        setContentView(R.layout.activity_white_noise_player);
        init();
        setListener();

        controller = WhiteNoisePlayerService.getController();

        switch(WhiteNoisePlayerService.getPlayState()){
            case WhiteNoisePlayerService.PREPARING:
                player.setBackgroundResource(R.mipmap.play);
                linearLayout.setBackgroundResource(R.color.c_playing);
                musicCenter1.setAlpha(0f);
                musicCenter2.setAlpha(1f);
            case WhiteNoisePlayerService.NONE:
            case WhiteNoisePlayerService.PAUSE:
                player.setBackgroundResource(R.mipmap.play);
                linearLayout.setBackgroundResource(R.color.c_playing);
                musicCenter1.setAlpha(1f);
                musicCenter2.setAlpha(0f);
                break;
            case WhiteNoisePlayerService.PLAYING:
                player.setBackgroundResource(R.mipmap.play2);
                linearLayout.setBackgroundResource(R.color.c_playing);
                musicCenter1.setAlpha(0f);
                musicCenter1.setAlpha(1f);
                break;
        }
        new Thread() {
            @Override
            public void run() {
                //这里写入子线程需要做的工作
                queryFavoriteW(WhiteNoisePlayerService.getAudioInfos().get(0).getAudioId());
            }
        }.start();
    }

    private void setImage() {
        List<AudioInfo> audioInfos = WhiteNoisePlayerService.getAudioInfos();
        if(audioInfos.size() >= 1){
            RequestBuilder builder = Glide.with(this)
                    .load(audioInfos.get(0).getAudioPic());
            builder.into(musicPic1);
            builder.into(voiceImg1);

        }
        if(audioInfos.size() >= 2){
            RequestBuilder builder = Glide.with(this)
                    .load(audioInfos.get(1).getAudioPic());
            builder.into(musicPic2);
            builder.into(voiceImg2);
        }
        if(audioInfos.size() >= 3){
            RequestBuilder builder = Glide.with(this)
                    .load(audioInfos.get(2).getAudioPic());
            builder.into(musicPic3);
            builder.into(voiceImg3);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WhiteNoisePlayerService.removeForListener(handler);
    }

    private void setListener(){
        MyListener myListener = new MyListener();
        setting.setOnClickListener(myListener);
        player.setOnClickListener(myListener);
        share.setOnClickListener(myListener);
        like.setOnClickListener(myListener);
        list.setOnClickListener(myListener);
        alarm.setOnClickListener(myListener);
    }
    private class MyListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.white_noise_setting:
                    settingPopup.popupWindow();
                    break;
                case R.id.white_noise_play:
                    switch(WhiteNoisePlayerService.getPlayState()){
                        case WhiteNoisePlayerService.PLAYING:
                            controller.pausePlay(true);
                            break;
                        case WhiteNoisePlayerService.PAUSE:
                            controller.continuePlay(true);
                            break;
                        case WhiteNoisePlayerService.NONE:
                            Toast.makeText(WhiteNoisePlayerActivity.this,"没有要播放的白噪音组合，再去逛逛吧",Toast.LENGTH_LONG).show();;
                            break;
                        case WhiteNoisePlayerService.PREPARING:
                            Toast.makeText(WhiteNoisePlayerActivity.this,"正在加载中，请稍等",Toast.LENGTH_LONG).show();
                            break;
                    }
                    break;

                case R.id.white_noise_palyer_share:
                    if("SleepFriendCreate".equals(WhiteNoisePlayerService.getChannel())){
                        Toast.makeText(WhiteNoisePlayerActivity.this,"不能直接抄袭其他眠友的作品哦",Toast.LENGTH_LONG).show();
                        break;
                    }
                    Intent intent = new Intent(v.getContext(), VoiceDescribeActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mlist",new ArrayList(WhiteNoisePlayerService.getAudioInfos()));
                    bundle.putString("channel",WhiteNoisePlayerService.getChannel());
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.white_noise_alarm:
                    showDialog();
                    break;
                case R.id.white_noise_list:
                    intentToHistory = new Intent(v.getContext(), PlayHistoryActivity.class);
                    startActivity(intentToHistory);
                    break;
                case R.id.white_noise_like:
                    if(!isFavorite){
                        isFavorite = true;
                        like.setBackgroundResource(R.mipmap.like2);
                        addFavorite(WhiteNoisePlayerService.getAudioInfos());
                    }else{
                        isFavorite = false;
                        like.setBackgroundResource(R.mipmap.nolike);
                        deleteFavorite(WhiteNoisePlayerService.getAudioInfos().get(0).getAudioId());
                    }
                    break;
            }
        }
    }

    private void showDialog() {
        timer2 = new Timer();
        timerTask.cancel();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                //时间到停止播放
                if (WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING){
                    controller.pausePlay(true);
                }
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(WhiteNoisePlayerActivity.this);
        builder.setTitle("选择定时播放的时长(分钟)");
        // 指定下拉列表的显示数据
        final String[] times = { "5", "15", "30", "45", "60" };
        // 设置一个下拉的列表选择项
        builder.setItems(times, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING){
                    Toast.makeText(WhiteNoisePlayerActivity.this, "选择的时间为：" + times[which], Toast.LENGTH_SHORT).show();
                    timer2.schedule(timerTask , Integer.parseInt(times[which]) * 60 * 1000);
                }else{
                    Toast.makeText(WhiteNoisePlayerActivity.this, "当前没有在播放", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }

    private void deleteFavorite(String whiteId1){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "Favorite/deleteFavoriteW?userId=" + user.getUserId() + "&whiteId1=" + whiteId1)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("返回", "取消收藏");
                isFavorite = false;
            }
        });
    }

    private void addFavorite(List<AudioInfo> audioInfos){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body;
        if (audioInfos.size() == 3){
            body = new FormBody.Builder()
                    .add("userId", user.getUserId())
                    .add("isWhite", "1")
                    .add("whiteId1", audioInfos.get(0).getAudioId())
                    .add("whiteUrl1", audioInfos.get(0).getAudioUrl())
                    .add("whiteName1", audioInfos.get(0).getAudioName())
                    .add("whiteId2", audioInfos.get(1).getAudioId())
                    .add("whiteUrl2", audioInfos.get(1).getAudioUrl())
                    .add("whiteName2", audioInfos.get(1).getAudioName())
                    .add("whiteId3", audioInfos.get(2).getAudioId())
                    .add("whiteUrl3", audioInfos.get(2).getAudioUrl())
                    .add("whiteName3", audioInfos.get(2).getAudioName())
                    .add("whitePic1", audioInfos.get(0).getAudioPic())
                    .add("whitePic2", audioInfos.get(1).getAudioPic())
                    .add("whitePic3", audioInfos.get(2).getAudioPic())
                    .add("collectTime", dateFormat.format(date))
                    .build();
        }else if(audioInfos.size() == 2){
            body = new FormBody.Builder()
                    .add("userId", user.getUserId())
                    .add("isWhite", "1")
                    .add("whiteId1", audioInfos.get(0).getAudioId())
                    .add("whiteUrl1", audioInfos.get(0).getAudioUrl())
                    .add("whiteName1", audioInfos.get(0).getAudioName())
                    .add("whiteId2", audioInfos.get(1).getAudioId())
                    .add("whiteUrl2", audioInfos.get(1).getAudioUrl())
                    .add("whiteName2", audioInfos.get(1).getAudioName())
                    .add("whitePic1", audioInfos.get(0).getAudioPic())
                    .add("whitePic2", audioInfos.get(1).getAudioPic())
                    .add("collectTime", dateFormat.format(date))
                    .build();
        }else{
            body = new FormBody.Builder()
                    .add("userId", user.getUserId())
                    .add("isWhite", "1")
                    .add("whiteId1", audioInfos.get(0).getAudioId())
                    .add("whiteUrl1", audioInfos.get(0).getAudioUrl())
                    .add("whiteName1", audioInfos.get(0).getAudioName())
                    .add("whitePic1", audioInfos.get(0).getAudioPic())
                    .add("collectTime", dateFormat.format(date))
                    .build();
        }
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "Favorite/createFavoriteW")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("aaa", "添加成功");
            }
        });
    }

    private void queryFavoriteW(String audioId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/queryFavoriteW?userId=" + user.getUserId())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Gson gson = new Gson();
                Result result = gson.fromJson(str, new TypeToken<Result<List<Favorite>>>(){}.getType());
                List<Favorite> audioInfo = (List<Favorite>) result.getData();
                int i = 0;
                while (i < audioInfo.size()){
                    if (audioInfo.get(i).getIsWhite() == 1){
                        if (audioInfo.get(i).getWhiteId1().equals(audioId)){
                            isFavorite = true;
                            break;
                        }else{
                            isFavorite = false;
                        }
                        i++;
                    }else {
                        i++;
                    }
                }
                Message message = new Message();
                message.what = 7;
                handler.sendMessage(message);
            }
        });
    }

    private void init(){
        musicPic1 = findViewById(R.id.music_pic1);
        musicPic2 = findViewById(R.id.music_pic2);
        musicPic3 = findViewById(R.id.music_pic3);
        //播放的控件
        player = findViewById(R.id.white_noise_play);
        //设置按钮按钮
        setting = findViewById(R.id.white_noise_setting);
        //分享按钮
        share = findViewById(R.id.white_noise_palyer_share);
        //闹钟按钮
        alarm = findViewById(R.id.white_noise_alarm);
        //喜欢按钮
        like = findViewById(R.id.white_noise_like);
        //列表按钮
        list = findViewById(R.id.white_noise_list);
        user = (User) getApplication();
        linearLayout = findViewById(R.id.white_noise_linearLayout);
        musicCenter1 = findViewById(R.id.white_noise_music_center1);
        musicCenter2 = findViewById(R.id.white_noise_music_center2);

        //为滑动条添加事件监听，每个控件不同果然点击事件方法名都不同

        animator1 = ObjectAnimator.ofInt(linearLayout,"backgroundColor",getResources().getColor(R.color.c_playing),getResources().getColor(R.color.c_pause));
        animator1.setDuration(500);
        animator1.setEvaluator(new ArgbEvaluator());

        animator2 = ObjectAnimator.ofInt(linearLayout,"backgroundColor",getResources().getColor(R.color.c_pause),getResources().getColor(R.color.c_playing));
        animator2.setDuration(500);
        animator2.setEvaluator(new ArgbEvaluator());


        animator3 = ValueAnimator.ofFloat(0f,1f);
        animator3.setDuration(500);
        animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                musicCenter1.setAlpha(1 - alpha);
                musicCenter2.setAlpha(alpha);
            }
        });

        animator4 = ValueAnimator.ofFloat(0f,1f);
        animator4.setDuration(500);
        animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                musicCenter2.setAlpha(1 - alpha);
                musicCenter1.setAlpha(alpha);
            }
        });
        settingPopup = new PopupAndDarkenWindow(this,R.layout.popup_white_noise_setting);
        settingPopup.setLayoutParam(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        settingPopup.setPopupViewListener(new PopupAndDarkenWindow.SetPopupViewListenerCallBack() {
            @Override
            public void setListener(View v, PopupAndDarkenWindow popupAndDarkenWindow) {
                initSettingPopupView(v,popupAndDarkenWindow);
            }
        });
        settingPopup.init();
        setImage();
        setVoice();
    }

    private void setVoice() {
        voiceBar1.setProgress(WhiteNoisePlayerService.getVoice1());
        voiceBar2.setProgress(WhiteNoisePlayerService.getVoice2());
        voiceBar3.setProgress(WhiteNoisePlayerService.getVoice3());
        List<AudioInfo> audioInfos = WhiteNoisePlayerService.getAudioInfos();
        if(audioInfos.size() == 1){
            voice1.setVisibility(View.VISIBLE);
            voice2.setVisibility(View.INVISIBLE);
            voice3.setVisibility(View.INVISIBLE);
        }else if(audioInfos.size() == 2){
            voice1.setVisibility(View.VISIBLE);
            voice2.setVisibility(View.VISIBLE);
            voice3.setVisibility(View.INVISIBLE);
        }else{
            voice1.setVisibility(View.VISIBLE);
            voice2.setVisibility(View.VISIBLE);
            voice3.setVisibility(View.VISIBLE);
        }
    }

    //对PopupAndDarkenWindow中的布局中的各种控件进行初始化，监听器设置
    //不需要在自行在任何地方调用，只需要在初始化PopupAndDarkenWindow的地方调用
    private void initSettingPopupView(View v, PopupAndDarkenWindow popupAndDarkenWindow) {

        voiceImg1 = v.findViewById(R.id.voice_image1);
        voiceImg2 = v.findViewById(R.id.voice_image2);
        voiceImg3 = v.findViewById(R.id.voice_image3);
        voiceBar1 = v.findViewById(R.id.voice_seekbar1);
        voiceBar2 = v.findViewById(R.id.voice_seekbar2);
        voiceBar3 = v.findViewById(R.id.voice_seekbar3);
        voice1 = v.findViewById(R.id.voice1);
        voice2 = v.findViewById(R.id.voice2);
        voice3 = v.findViewById(R.id.voice3);
        SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                switch(seekBar.getId()){
                    case R.id.voice_seekbar1:
                        controller.setVolume1(progress);
                        break;
                    case R.id.voice_seekbar2:
                        controller.setVolume2(progress);
                        break;
                    case R.id.voice_seekbar3:
                        controller.setVolume3(progress);
                        break;
                }
            }
        };
        voiceBar1.setOnSeekBarChangeListener(seekBarChangeListener);
        voiceBar2.setOnSeekBarChangeListener(seekBarChangeListener);
        voiceBar3.setOnSeekBarChangeListener(seekBarChangeListener);

    }

    //handler机制，可以理解为线程间的通信，我获取到一个信息，然后把这个信息告诉你，就这么简单
    public Handler handler = new Handler(Looper.getMainLooper()){//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 7:
                    if (isFavorite){
                        like.setBackgroundResource(R.mipmap.like2);
                    }else{
                        like.setBackgroundResource(R.mipmap.nolike);
                    }
                    break;
                case WhiteNoisePlayerService.START_EVENT:
                    //开始播放事件
                    setImage();
                    setVoice();
                    player.setBackgroundResource(R.mipmap.play);
                    break;
                case WhiteNoisePlayerService.PREPARED_EVENT:
                    //准备完成事件
                    player.setBackgroundResource(R.mipmap.play2);
                    break;
                case WhiteNoisePlayerService.CONTINUE_EVENT:
                    //发生开始继续播放事件
                    player.setBackgroundResource(R.mipmap.play2);
                    animator2.start();
                    animator4.start();
                    break;
                case WhiteNoisePlayerService.PAUSE_EVENT:
                    //发生暂停播放事件
                    player.setBackgroundResource(R.mipmap.play);
                    animator1.start();
                    animator3.start();
                    break;
                case WhiteNoisePlayerService.ERROR_EVENT:
                    player.setBackgroundResource(R.mipmap.play);
                    animator1.start();
                    animator3.start();
                    Toast.makeText(WhiteNoisePlayerActivity.this,"播放器出错了，啥错我不知道",Toast.LENGTH_LONG).show();
                    break;
            }

        }
    };

}